
// lib
import axios from "axios";
// local_models
import hotCity from "./components/HotCity.vue";
import cityTabs from "./components/CityTabs.vue";
import cityList from "./components/CityList.vue";

export default {
  name: "xrkSelector",
  model: {
    prop: "visible",
    event: "change",
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    areaCode: {
      type: String,
      default: "",
    },
  },
  components: {
    hotCity,
    cityTabs,
    cityList,
  },
  data() {
    return {
      defualtApi: "https://supertest.xrkbx.com/mall_products/chooseLocation/YGRS/YG_YGRS_0004",
      cityList: {
        cities: [], // 省 -> 市(子级)
        city_areas: [], // 市 -> 区(子级)
        area_towns: [], // 区 -> 街道(子级)
        hotcitys: [], // 热门城市
        provinces: [], // 省
      },
      cityHeadTabs: [
        // 当前列表上方所选的城市tab
        {
          id: -1,
          name: "全部",
        },
      ],
      currentCityList: [
        // 当前用于渲染城市列表的数据
      ],
      cityHeadTabsIndex: 0, // 当前选择选项卡的顺序
    };
  },
  watch: {
    visible: {
      handler(newVal) {
        if (newVal) {
          if (this.cache) return;
          const loading = this.$loading.create({ message: "加载中..." });
          axios
            .get(this.areaApi)
            .then((response) => {
              this.cityList = response.data;
              this.currentCityList.splice(0, 0, this.cityList.cities);
              this.cityList.hotcitys = this.cityList.hotcitys || [];
              loading.remove();
            })
            .catch((err) => {
              console.log(err);
              loading.remove();
            });
        }
      },
    },
  },
  computed: {
    cache() {
      return this.cityList.provinces.length > 0;
    },
    areaApi() {
      return this.areaCode || this.defualtApi;
    },
    currentType() {
      // 当前选中的区域层级
      const areaMap = {
        0: "provinces", // 省
        1: "cities", // 市
        2: "city_areas", // 区
        3: "area_towns", // 街道
      };
      return areaMap[this.cityHeadTabsIndex + 1];
    },
  },
  mounted() { },
  methods: {
    onClose() {
      this.$emit("change", !this.visible);
    },
    // 点击上方tab的切换
    onChangeCityTabs(index) {
      this.cityHeadTabsIndex = index;
    },
    // 选择下一城市区域
    onChangeCityList(city) {
      this.cityHeadTabs = this.fetchNextcityHeadTabs(city, this.currentType);
      this.currentCityList = this.filtersCityLIst(city, this.currentType);
      this.$nextTick(() => {
        this.cityHeadTabsIndex = this.cityHeadTabs.length - 1;
      });
    },

    /**
     * @description: 热门城市选择
     * @param {Array} cityHeadTabs 已经选择城市tab数据
     * @param {Array} citiesArray 省(直辖市)列表数据
     * @param {Array} areasArray  县市级以及地区列表数据
     * @return {*}
     */
    onChceHotCity(cityHeadTabs, citiesArray, areasArray) {
      this.cityHeadTabs.splice(1);
      this.cityHeadTabs.push(...cityHeadTabs);
      citiesArray = this.filtersData(citiesArray, "cities");
      areasArray = this.filtersData(areasArray, "city_areas");
      this.currentCityList.splice(1);
      this.currentCityList.push(...[citiesArray, areasArray]);
      this.$nextTick(() => {
        this.cityHeadTabsIndex = 2;
      });
    },
    // 提交最终的数据
    submit(city) {
      const cityArray = this.deepClone(this.cityHeadTabs);
      cityArray.shift();
      cityArray.push({
        name: city.name,
        id: city.code,
      });
      let cityName = cityArray
        .map((item) => {
          return item.name;
        })
        .join("-");
      let lastCityName = cityName.split("-");
      lastCityName = lastCityName[lastCityName.length - 1];

      let cityId = cityArray
        .map((item) => {
          return item.id;
        })
        .join("-");

      let lastCityId = cityId.split("-");
      lastCityId = lastCityId[lastCityId.length - 1];

      this.$emit("change", !this.visible);
      this.$emit("submit", {
        cityName,
        lastCityName,
        cityId,
        lastCityId,
      });
    },
    // 更新tabs的数据
    fetchNextcityHeadTabs(city, type) {
      city = this.filtersCity(city, type);
      this.cityHeadTabs.splice(this.cityHeadTabsIndex + 1);
      this.cityHeadTabs.push(city);
      return this.cityHeadTabs;
    },
    // utils
    deepClone(obj) {
      return JSON.parse(JSON.stringify(obj));
    },
    // 由于各区域的字段名称都不统一,故此函数做统一数据格式处理
    filtersCityLIst(data, areaType) {
      if (areaType === "cities") {
        this.currentCityList[1] = this.filtersData(data.cities, "cities");
      } else if (areaType === "city_areas") {
        const city_areasArray = this.cityList.city_areas.find((item) => {
          return item.code === data.id;
        });
        this.currentCityList[2] = this.filtersData(
          city_areasArray.childs,
          "city_areas"
        );
      } else if (areaType === "area_towns") {
        const area_townsArray = this.cityList.area_towns.find((item) => {
          return item.code === data.code;
        });
        this.currentCityList[3] = this.filtersData(
          area_townsArray.childs,
          "area_towns"
        );
      }
      return this.currentCityList;
    },
    // 统一字段处理
    filtersCity(data, type) {
      switch (type) {
        case "cities":
          data = {
            name: data.province_name,
            id: data.province_id,
          };
          break;
        case "city_areas":
          data = {
            name: data.city_name,
            id: data.id,
          };
          break;
        case "area_towns":
          data = {
            name: data.name,
            id: data.code,
          };
          break;
        default:
          break;
      }
      return data;
    },
    // 理由同上
    filtersData(data, type) {
      switch (type) {
        case "cities":
          data = data.map((item) => {
            return {
              ...item,
              province_name: item.city_name,
              province_id: item.id,
            };
          });
          break;
        case "city_areas":
          data = data.map((item) => {
            return {
              ...item,
              province_name: item.name,
              province_id: item.code,
            };
          });
          break;
        case "area_towns":
          data = data.map((item) => {
            return {
              ...item,
              province_name: item.name,
              province_id: item.code,
            };
          });
          break;
        default:
          break;
      }
      return data;
    },
  },
};